﻿using BZ.Core.Frm;
using NDK.Motion.MachineManager;
using NDK.Motion.MachineResources;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NDK.Motion.Frm
{
    public partial class Frm_MotionConfig : Form
    {
        private static log4net.ILog traceLogger = log4net.LogManager.GetLogger("Frm_MotionConfig");

        /// <summary>
        /// 当前选中的工位
        /// </summary>
        private string curStation = "";
        private string lastStation = "";
        private Frm_MotionConfig()
        {
            InitializeComponent();
            //
            dgv_Home.AutoGenerateColumns = false;
            dgv_Home.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList);

            dgv_AxisPara.AutoGenerateColumns = false;
            dgv_AxisPara.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList);
        }

        private static Frm_MotionConfig _instance;
        private static readonly object singletonLock = new object();
        public static Frm_MotionConfig Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null || _instance.IsDisposed)
                        {
                            _instance = new Frm_MotionConfig();
                        }
                    }
                }
                return _instance;
            }
        }
        private void Frm_MotionConfig_Load(object sender, EventArgs e)
        {
            if (MachineDataManager.Instance.StationList == null) return;

            dgv_Station.DataSource = new BindingList<Station>(MachineDataManager.Instance.StationList);
            if (MachineDataManager.Instance.StationList.Count > 0)
            {
                curStation = MachineDataManager.Instance.StationList[0].StationName;
            }

            nud_SpeedPercentage.Value = (decimal)MachineDataManager.Instance.MotionSpeedPercentage;
        }
        private void cms_Station_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == tsmi_Add)
            {
                Frm_AddStation addStationForm = new Frm_AddStation();
                if (addStationForm.ShowDialog(this) == DialogResult.OK)
                {
                    dgv_Station.DataSource = new BindingList<Station>(MachineDataManager.Instance.StationList);
                }
            }
            if (e.ClickedItem == tsmi_Modify)
            {
                Frm_ModifyStation modifyStationForm = new Frm_ModifyStation();
                string stationName = dgv_Station.CurrentRow.Cells["cStationName"].Value.ToString();
                Station station = MachineDataManager.Instance.StationList.Find(s => s.StationName == stationName);
                modifyStationForm.station = station;
                curStation = stationName;
                if (MachineDataManager.Instance.PositionList.FindAll(p => p.Station == curStation)?.Count > 0)
                {
                    if (MessageBox.Show(this, "确认修改工位吗？\r\n修改后该工位下的点位将被清除！", "确认修改", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        if (modifyStationForm.ShowDialog(this) == DialogResult.OK)
                        {
                            MachineDataManager.Instance.DeletePositionTable(modifyStationForm.station.StationName);
                            GeneratePositionTable(modifyStationForm.station.StationName);
                            MachineDataManager.Instance.PositionList.RemoveAll(p => p.Station == curStation);
                            dgv_Station.DataSource = new BindingList<Station>(MachineDataManager.Instance.StationList);
                        }
                    }
                }

            }
            if (e.ClickedItem == tsmi_Update)
            {
                dgv_Station.DataSource = new BindingList<Station>(MachineDataManager.Instance.StationList);
            }
            if (e.ClickedItem == tsmi_Save)
            {
                MachineDataManager.SaveToFile();
            }
            if (e.ClickedItem == tsmi_Delete)
            {
                string stationName = dgv_Station.CurrentRow.Cells["cStationName"].Value.ToString();
                Station station = MachineDataManager.Instance.StationList.Find(s => s.StationName == stationName);
                if (station != null)
                {
                    if (MessageBox.Show(this, "确认删除工位吗？\r\n删除后该工位下的点位将被清除！", "确认修改", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {

                        MachineDataManager.Instance.DeletePositionTable(stationName);
                        MachineDataManager.Instance.PositionList.RemoveAll(p => p.Station == curStation);
                        MachineDataManager.Instance.StationList.Remove(station);
                        dgv_Station.DataSource = new BindingList<Station>(MachineDataManager.Instance.StationList);
                    }

                }
            }
        }

        private void dgv_Station_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //根据选中的工站生成点位表的列
            if (e.RowIndex >= 0)
            {
                string stationName = dgv_Station.Rows[e.RowIndex].Cells["cStationName"].Value.ToString();
                lastStation = curStation;
                curStation = stationName;
                dgv_PositionTable.DataSource = MachineDataManager.Instance.LocalPostion[stationName];
            }
        }

        /// <summary>
        /// 生成对应工位的点位表配置文件，并绑定到界面dgv_PositionTable
        /// </summary>
        /// <param name="stationName"></param>
        private void GeneratePositionTable(string stationName)
        {
            Station station = MachineDataManager.Instance.StationList.Find(s => s.StationName == stationName);
            if (station == null)
            {
                return;
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("Guid", Type.GetType("System.String"));
            dt.Columns.Add("点位名称", Type.GetType("System.String"));
            dt.Columns.Add("执行顺序", Type.GetType("System.UInt32"));
            dt.Columns.Add("轴优先级", Type.GetType("System.UInt32"));

            foreach (var axis in station.AxisList)
            {
                dt.Columns.Add(axis.Name, Type.GetType("System.Double"));
            }
            dt.Columns.Add("功能类型", Type.GetType("System.String"));
            dt.Columns.Add("点位描述", Type.GetType("System.String"));
            dt.Columns.Add("是否执行", Type.GetType("System.Boolean"));
            dt.Columns.Add("是否统一设定", Type.GetType("System.Boolean"));
            dt.Columns.Add("工站", Type.GetType("System.String"));
            //删除点位表DataGridView中的轴列
            if (lastStation != curStation && lastStation != "")
            {
                Station LastStation = MachineDataManager.Instance.StationList.Find(s => s.StationName == lastStation);
                string axisNames = "";
                foreach (DataGridViewColumn c in dgv_PositionTable.Columns)
                {
                    if (c.HeaderText.Contains("X") || c.HeaderText.Contains("Y") || c.HeaderText.Contains("Z")
                        || c.HeaderText.Contains("U") || c.HeaderText.Contains("V") || c.HeaderText.Contains("R"))
                    {
                        axisNames = string.IsNullOrWhiteSpace(axisNames) ? c.HeaderText : axisNames + "," + c.HeaderText;
                    }
                }

                foreach (var axisName in axisNames.Split(','))
                {
                    if (string.IsNullOrWhiteSpace(axisNames)) continue;
                    if (!dgv_PositionTable.Columns.Contains(axisName)) continue;
                    dgv_PositionTable.Columns.Remove(axisName);
                }
            }
            //重新绑定当前选中工站的点位表（如果本地没有该工位的点位表，则生成一个，否则从本地读出来显示到界面）

            if (!MachineDataManager.Instance.IsExistPositionTable(stationName))
            {
                MachineDataManager.Instance.SavePositionTable(dt, stationName);
            }
            else
            {
                dt = MachineDataManager.Instance.LoadPositionTable(stationName);
            }
            dgv_PositionTable.DataSource = dt;
            //自动同步一下
            SynchronizeUIToLocal();
        }
        private void cms_Path_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            dgv_PositionTable.EndEdit();
            DataTable dt = dgv_PositionTable.DataSource as DataTable;
            //添加点位
            if (e.ClickedItem == tsmi_AddPos)
            {
                if (string.IsNullOrEmpty(curStation))
                {
                    MessageBox.Show("请选中工站！");
                    return;
                }
                Frm_AddPosition addPosForm = new Frm_AddPosition();
                addPosForm.CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == curStation);
                if (addPosForm.ShowDialog(this) == DialogResult.OK)
                {
                    //得到新加的点位,并显示到界面
                    Position position = addPosForm.NewPos;
                    AddPosToUI(dt, position);
                }
            }
            //保存点位：同步界面到本地csv和资源列表
            if (e.ClickedItem == tsmi_SavePos)
            {
                SynchronizeUIToLocal();
            }
            //复制一个点位
            if (e.ClickedItem == tsmi_CopyPos)
            {
                if (dgv_PositionTable.SelectedRows.Count > 0)
                {
                    //得到界面选中的点位
                    string posGuid = dgv_PositionTable.SelectedRows[0].Cells["cGuid"].Value.ToString();
                    //查询到要复制的点位对象，然后复制并添加到点位资源列表中
                    Position pos = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == posGuid);
                    if (pos == null) return;

                    Position copyPos = pos.DeepCopy();
                    copyPos.PositionName += "-复制";
                    MachineDataManager.Instance.PositionList.Add(copyPos);
                    //在界面添加一行(显示复制的点位)
                    AddPosToUI(dt, copyPos);
                    //同步到csv和资源列表
                    //SynchronizeUIToLocal();//自动保存
                }
            }
            //示教一个点位的坐标
            if (e.ClickedItem == tsmi_Teaching)
            {
                if (dgv_PositionTable.SelectedRows.Count > 0)
                {
                    //得到点位
                    string posGuid = dgv_PositionTable.SelectedRows[0].Cells["cGuid"].Value.ToString();
                    Position pos = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == posGuid);
                    foreach (var axis in pos.AxisList)
                    {
                        dgv_PositionTable.SelectedRows[0].Cells[axis.Name].Value = axis.GetPos();
                        // dgv_PositionTable.SelectedRows[0].Cells[axis.AxisName].Value = 10.0;
                    }
                }
            }

            if (e.ClickedItem == tsmi_VelProfile)
            {
                Frm_VelProfile vpFrm = new Frm_VelProfile();
                //传入当前工站
                vpFrm.CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == curStation);
                //传入选中行点位
                if (dgv_PositionTable.SelectedRows.Count > 0)
                {
                    vpFrm.CurPositionTable = dgv_PositionTable.SelectedRows[0];

                    string posGuid = dgv_PositionTable.SelectedRows[0].Cells["cGuid"].Value.ToString();
                    vpFrm.CurPosition = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == posGuid);
                    var ssdas = MachineDataManager.Instance.PositionList.FindAll(x => x.Guid == posGuid);
                    vpFrm.ShowDialog(this);
                }
            }
            if (e.ClickedItem == tsmi_DeletePos)
            {
                if (dgv_PositionTable.SelectedRows.Count > 0)
                {
                    if (MessageBox.Show(this, "确认删除选中点位吗？", "确认修改", MessageBoxButtons.OKCancel) != DialogResult.OK) return;

                    for (int i = 0; i < dgv_PositionTable.SelectedRows.Count; i++)
                    {
                        string posGuid = dgv_PositionTable.SelectedRows[i].Cells["cGuid"].Value.ToString();
                        Position pos = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == posGuid);
                        //删除资源列表数据
                        MachineDataManager.Instance.PositionList.Remove(pos);
                        //删除界面表格数据
                        dgv_PositionTable.Rows.Remove(dgv_PositionTable.SelectedRows[i]);
                    }
                    //SynchronizeUIToLocal();//自动保存
                }
            }
            if (e.ClickedItem == tsmi_MoveTo)
            {
                if (dgv_PositionTable.SelectedRows.Count > 0)
                {
                    string posGuid = dgv_PositionTable.SelectedRows[0].Cells["cGuid"].Value.ToString();
                    Position pos = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == posGuid);
                    if (pos != null)
                    {
                        MotionControl.AxesMove(pos);
                    }
                    else
                    {
                        MessageBox.Show(this, "选中的点位不存在!", "确认框", MessageBoxButtons.OK);
                    }
                }
            }
        }
        private void tsmi_SinglePositionVelSetting_Click(object sender, EventArgs e)
        {
            //速度剖面设置
            {
                Frm_VelProfile vpFrm = new Frm_VelProfile();
                //传入当前工站
                vpFrm.CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == curStation);
                //传入选中行点位
                if (dgv_PositionTable.SelectedRows.Count > 0)
                {
                    vpFrm.CurPositionTable = dgv_PositionTable.SelectedRows[0];

                    string posGuid = dgv_PositionTable.SelectedRows[0].Cells["cGuid"].Value.ToString();
                    vpFrm.CurPosition = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == posGuid);
                    vpFrm.ShowDialog(this);
                }

            }
        }

        private void tsmi_GloblePositionVelSetting_Click(object sender, EventArgs e)
        {
            Dlg_UniformVelocity dlg_UniformVelocity = new Dlg_UniformVelocity();
            DialogResult res = dlg_UniformVelocity.ShowDialog(this);
        }
        /// <summary>
        /// 添加一个点位到界面
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pos"></param>
        private void AddPosToUI(DataTable dt, Position pos)
        {
            DataRow dr = dt.Rows.Add();
            dr["Guid"] = pos.Guid;
            dr["点位名称"] = pos.PositionName;
            dr["执行顺序"] = pos.PositionOrder;
            dr["轴优先级"] = pos.AxisPriority;
            dr["功能类型"] = pos.Function;
            dr["点位描述"] = pos.Description;
            dr["是否执行"] = pos.IsRun;
            dr["是否统一设定"] = pos.IsAllowUniform;
            dr["工站"] = curStation;
            Station CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == curStation);
            foreach (var axis in CurStation.AxisList)
            {
                dr[axis.Name] = 0.0;
            }
            dgv_PositionTable.DataSource = dt;
        }

        /// <summary>
        /// 同步界面点位到资源列表和csv(如果用户在本地直接创建了点位，这时候也需要同步)
        /// 为什么需要同步？因为界面的修改，不能直接绑定到资源列表，如果直接绑定的话，不点保存就会直接生效
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        //private void SynchronizeUIToLocal()
        //{
        //    DataTable dt = dgv_PositionTable.DataSource as DataTable;

        //    if (dt != null)
        //    {
        //        foreach (DataRow dr in dt.Rows)
        //        {
        //            Position pos = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == dr["Guid"].ToString());
        //            if (pos == null)//界面有，资源列表没有（人工在CSV中加的点位）
        //            {
        //                pos = new Position();
        //                pos.Guid = dr["Guid"].ToString();
        //                pos.PositionName = dr["点位名称"].ToString();
        //                pos.PositionOrder = int.Parse(dr["执行顺序"].ToString());
        //                pos.AxisPriority = dr["轴优先级"].ToString();
        //                pos.Function = dr["功能类型"].ToString();
        //                pos.Description = dr["点位描述"].ToString();
        //                pos.IsRun = bool.Parse(dr["是否执行"].ToString());
        //                pos.Station = dr["工站"].ToString();

        //                Station CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == pos.Station);
        //                foreach (var axis in CurStation.AxisList)
        //                {
        //                    VelocityProfile vp = new VelocityProfile();
        //                    vp.AxisName = axis.Name;
        //                    vp.Acc = 100.0;
        //                    vp.Dec = 100.0;
        //                    vp.MoveVel = 10;
        //                    vp.StartVel = 5;

        //                    double position = 0.0;
        //                    double.TryParse(dr[axis.Name].ToString(), out position);
        //                    vp.Pos = position;

        //                    pos.VelocityProfiles.Add(vp);
        //                    pos.AxisList.Add(axis);
        //                }
        //                MachineDataManager.Instance.PositionList.Add(pos);
        //            }
        //            else//界面和资源列表都有，将界面数据更新到资源列表
        //            {
        //                pos.PositionOrder = int.Parse(dr["执行顺序"].ToString());
        //                pos.PositionName = dr["点位名称"].ToString();
        //                pos.AxisPriority = dr["轴优先级"].ToString();
        //                pos.Function = dr["功能类型"].ToString();
        //                pos.Description = dr["点位描述"].ToString();
        //                pos.IsRun = bool.Parse(dr["是否执行"].ToString());

        //                Station CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == pos.Station);
        //                foreach (var axis in CurStation.AxisList)
        //                {
        //                    VelocityProfile vp = pos.VelocityProfiles.SingleOrDefault(v => v.AxisName == axis.Name);
        //                    double position = 0.0;
        //                    double.TryParse(dr[axis.Name].ToString(), out position);
        //                    vp.Pos = position;
        //                }
        //            }
        //        }
        //        //同步完成后，将界面点位和内存数据保存到本地
        //        MachineDataManager.Instance.SavePositionTable(dt, curStation);
        //    }
        //}
        private void SynchronizeUIToLocal()
        {
            DataTable dt = dgv_PositionTable.DataSource as DataTable;

            if (dt != null)
            {
                var curStationPoss = MachineDataManager.Instance.PositionList.FindAll(p => p.Station == curStation);//备份当前工位在内存中的点位
                MachineDataManager.Instance.PositionList.RemoveAll(p => p.Station == curStation);//清空当前工位内存中的点位
                var posNameList = dt.AsEnumerable().Select(r => r.Field<string>("点位名称")).ToList();
                foreach (DataRow dr in dt.Rows)//重新将当前工位界面上的点位，添加到内存列表
                {
                    Position posTemp = curStationPoss.Find(p => p.Guid == dr["Guid"].ToString() && p.PositionName == dr["点位名称"].ToString());
                    var posNameCntInDt = posNameList.Count(x => x.Equals(dr["点位名称"].ToString()));
                    Position posNameTemp = curStationPoss.Find(p => p.PositionName == dr["点位名称"].ToString());
                    Position pos = new Position();
                    if (posTemp != null)//内存中有这个点的话，用这个点本来的速度剖面
                    {
                        pos = new Position();
                        pos.Guid = dr["Guid"].ToString();
                        pos.PositionName = dr["点位名称"].ToString();
                        pos.PositionOrder = int.Parse(dr["执行顺序"].ToString());
                        pos.AxisPriority = dr["轴优先级"].ToString();
                        pos.Function = dr["功能类型"].ToString();
                        pos.Description = dr["点位描述"].ToString();
                        pos.IsRun = bool.Parse(dr["是否执行"].ToString());
                        pos.IsAllowUniform = bool.Parse(dr["是否统一设定"].ToString());
                        pos.Station = dr["工站"].ToString();

                        Station CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == pos.Station);
                        foreach (var axis in CurStation.AxisList)
                        {
                            var oldPos = curStationPoss.SingleOrDefault(p => p.Guid == pos.Guid);
                            VelocityProfile vp = oldPos.VelocityProfiles.SingleOrDefault(v => v.AxisName == axis.Name);
                            double position = 0.0;
                            double.TryParse(dr[axis.Name].ToString(), out position);
                            vp.Pos = position;

                            pos.VelocityProfiles.Add(vp);
                            pos.AxisList.Add(axis);
                        }
                    }
                    else if (posNameTemp != null && posNameCntInDt == 1)//如果Guid在csv中手动改修改，搜索点位名称和唯一性
                    {
                        pos = new Position();
                        pos.Guid = dr["Guid"].ToString();
                        pos.PositionName = dr["点位名称"].ToString();
                        pos.PositionOrder = int.Parse(dr["执行顺序"].ToString());
                        pos.AxisPriority = dr["轴优先级"].ToString();
                        pos.Function = dr["功能类型"].ToString();
                        pos.Description = dr["点位描述"].ToString();
                        pos.IsRun = bool.Parse(dr["是否执行"].ToString());
                        pos.IsAllowUniform = bool.Parse(dr["是否统一设定"].ToString());
                        pos.Station = dr["工站"].ToString();

                        Station CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == pos.Station);
                        foreach (var axis in CurStation.AxisList)
                        {
                            var oldPos = posNameTemp;
                            VelocityProfile vp = oldPos.VelocityProfiles.SingleOrDefault(v => v.AxisName == axis.Name);
                            double position = 0.0;
                            double.TryParse(dr[axis.Name].ToString(), out position);
                            vp.Pos = position;

                            pos.VelocityProfiles.Add(vp);
                            pos.AxisList.Add(axis);
                        }
                    }
                    else//内存中没有这个点的话，生成一个默认的速度剖面
                    {
                        pos = new Position();
                        pos.Guid = dr["Guid"].ToString();
                        pos.PositionName = dr["点位名称"].ToString();
                        pos.PositionOrder = int.Parse(dr["执行顺序"].ToString());
                        pos.AxisPriority = dr["轴优先级"].ToString();
                        pos.Function = dr["功能类型"].ToString();
                        pos.Description = dr["点位描述"].ToString();
                        pos.IsRun = bool.Parse(dr["是否执行"].ToString());
                        pos.IsAllowUniform = bool.Parse(dr["是否统一设定"].ToString());
                        pos.Station = dr["工站"].ToString();

                        Station CurStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == pos.Station);
                        foreach (var axis in CurStation.AxisList)
                        {
                            VelocityProfile vp = new VelocityProfile();
                            //if (posTemp_NameList.Count > 0)
                            //{
                            //    var oldPos = curStationPoss.SingleOrDefault(p => p.PositionName == pos.PositionName);
                            //    vp = oldPos.VelocityProfiles.SingleOrDefault(v => v.AxisName == axis.Name);
                            //}
                            //else
                            {
                                vp.AxisId = axis.AxisID;
                                vp.AxisName = axis.Name;
                                vp.Acc = 100.0;
                                vp.Dec = 100.0;
                                vp.MoveVel = 10;
                                vp.StartVel = 5;

                            }

                            double position = 0.0;
                            double.TryParse(dr[axis.Name].ToString(), out position);
                            vp.Pos = position;

                            pos.VelocityProfiles.Add(vp);
                            pos.AxisList.Add(axis);
                        }
                    }
                    MachineDataManager.Instance.PositionList.Add(pos);
                }
                //同步完成后，将界面点位和内存数据保存到本地
                MachineDataManager.Instance.SavePositionTable(dt, curStation);
            }
        }

        #region 点位表输入数据检查
        private void dgv_PositionTable_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }

        /// <summary>
        /// 检查点位表中输入数据的合法性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_PositionTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            string guid = dgv_PositionTable.Rows[e.RowIndex].Cells["cGuid"].Value.ToString();
            Position pos = MachineDataManager.Instance.PositionList.SingleOrDefault(p => p.Guid == guid);
            if (pos == null) return;

            Station curStation = MachineDataManager.Instance.StationList.SingleOrDefault(s => s.StationName == pos.Station);
            if (curStation == null) return;

            foreach (var axis in curStation.AxisList)
            {
                double strPos = 0.0;

                if (!dgv_PositionTable.Columns.Contains(axis.Name)) return;
                if (double.TryParse(dgv_PositionTable.Rows[e.RowIndex].Cells[axis.Name].Value.ToString(), out strPos))
                {
                    if (strPos >= axis.SMel && strPos <= axis.SPel)
                    {
                        dgv_PositionTable.Rows[e.RowIndex].Cells[axis.Name].ErrorText = "";
                    }
                    else
                    {
                        dgv_PositionTable.Rows[e.RowIndex].Cells[axis.Name].ErrorText = "输入的值不在用户设定的软限位内！";
                    }
                }
                else
                {
                    dgv_PositionTable.Rows[e.RowIndex].Cells[axis.Name].ErrorText = "输入类型错误！";
                }
            }
        }
        private void dgv_PositionTable_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex < 0) return;
            //查找该工站下有没有同名的点位
            bool isExistrepete = false;
            int rowCount = dgv_PositionTable.Rows.Count;
            if (!dgv_PositionTable.Columns.Contains("点位名称")) return;
            for (int i = 0; i < rowCount; i++)
            {
                if (e.RowIndex != i)
                {
                    if (dgv_PositionTable.Rows[e.RowIndex].Cells["点位名称"].Value.ToString() == dgv_PositionTable.Rows[i].Cells["点位名称"].Value.ToString())
                    {
                        if (dgv_PositionTable.Rows[e.RowIndex].Cells["点位名称"].ErrorText == "")
                        {
                            dgv_PositionTable.Rows[e.RowIndex].Cells["点位名称"].ErrorText = "点位名称重复!";
                        }
                        isExistrepete = true;
                    }
                }
            }

            if (!isExistrepete)
            {
                dgv_PositionTable.Rows[e.RowIndex].Cells["点位名称"].ErrorText = "";
            }
            //检查每个点位的轴数量和优先级长度是否一致
            for (int i = 0; i < rowCount; i++)
            {
                string priority = dgv_PositionTable.Rows[i].Cells["AxisPriority"].Value.ToString();
                var pos = MachineDataManager.Instance.PositionList.Find(p => p.Guid == dgv_PositionTable.Rows[i].Cells["cGuid"].Value.ToString());
                List<VelocityProfile> axisList = new List<VelocityProfile>();
                if (pos == null)
                {
                    if (isExistrepete)
                    {
                        dgv_PositionTable.Rows[i].Cells["AxisPriority"].ErrorText = "优先级配置和未屏蔽的轴数量不一致!";
                        continue;
                    }
                    else
                        pos = MachineDataManager.Instance.PositionList.Find(p => p.PositionName == dgv_PositionTable.Rows[i].Cells["点位名称"].Value.ToString());

                }

                foreach (var v in pos.VelocityProfiles)
                {
                    if (v.Shield == false)
                    {
                        axisList.Add(v);
                    }
                }

                if (priority.Length != axisList.Count)
                {
                    dgv_PositionTable.Rows[i].Cells["AxisPriority"].ErrorText = "优先级配置和未屏蔽的轴数量不一致!";
                }
                else
                {
                    dgv_PositionTable.Rows[i].Cells["AxisPriority"].ErrorText = "";
                }
            }
        }

        #endregion
        private void cms_Home_Opening(object sender, CancelEventArgs e)
        {
            if (dgv_Home.SelectedRows.Count > 0)
            {
                string aixsName = dgv_Home.SelectedRows[0].Cells["home_AxisName"].Value.ToString();
                Axis axis = MachineDataManager.Instance.AxisList.SingleOrDefault(a => a.Name == aixsName);
                if (axis != null)
                {
                    if (axis.IsEnableHome == false)
                    {
                        tsmi_GoHome.Enabled = false;
                    }
                    else
                    {
                        tsmi_GoHome.Enabled = true;
                    }
                }
                else
                {
                    MessageBox.Show(this, "选中的轴不存在!", "确认框", MessageBoxButtons.OK);
                }
            }
        }
        private void cms_Home_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //tsmi_GoHome
            if (dgv_Home.SelectedRows.Count > 0)
            {
                string aixsName = dgv_Home.SelectedRows[0].Cells["home_AxisName"].Value.ToString();
                Axis axis = MachineDataManager.Instance.AxisList.SingleOrDefault(a => a.Name == aixsName);
                if (axis != null)
                {
                    if (axis.HomeMove() == false)
                    {
                        MessageBox.Show(this, "回零失败!", "确认框", MessageBoxButtons.OK);

                    }
                    Task.Run(() =>
                    {
                        var ret = axis.WaitHomeMoveDone(30 * 1000);
                        if (ret != 0)
                        {
                            string msg = "";
                            switch (ret)
                            {
                                case 1:
                                    msg = "超时停止";
                                    break;
                                case 2:
                                    msg = "外部命令停止";
                                    break;
                                case 3:
                                    msg = "掉使能停止";
                                    break;
                            }
                            MessageBox.Show(this, $"回零失败!失败原因：{msg}", "确认框", MessageBoxButtons.OK);
                        }

                    });
                }
                else
                {
                    MessageBox.Show(this, "选中的轴不存在!", "确认框", MessageBoxButtons.OK);
                }
            }
        }

        private void dgv_PositionTable_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 22)
            {
                DataGridViewUtils.PasteData(dgv_PositionTable);
            }
        }

        private void dgv_Home_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //for (int i = 0; i < dgv_Home.RowCount; i++)
            //{
            //    {
            //        dgv_Home.Rows[i].ReadOnly = true;
            //        dgv_Home.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
            //    }
            //}
        }

        private void dgv_AxisPara_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //for (int i = 0; i < dgv_AxisPara.RowCount; i++)
            //{
            //    if (i != 4 && i != 6)
            //    {
            //        dgv_AxisPara.Rows[i].ReadOnly = true;
            //        dgv_AxisPara.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
            //    }
            //}
            //for (int i = 0; i < dgv_AxisPara.ColumnCount; i++)
            //{
            //    if (i != 2)
            //    {
            //        dgv_AxisPara.Columns[i].ReadOnly = true;
            //        dgv_AxisPara.Columns[i].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
            //    }
            //}
        }

        private void dgv_PositionTable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //if (dgv_Station.Rows[0].Selected || dgv_Station.Rows[1].Selected)
            //{
            //    for (int i = 0; i < dgv_PositionTable.ColumnCount; i++)
            //    {
            //        if (i != 4 && i != 5 && i != 6)
            //        {
            //            dgv_PositionTable.Columns[i].ReadOnly = true;
            //            dgv_PositionTable.Columns[i].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
            //        }
            //    }
            //}
        }

        private void cms_Axis_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (tsmi_AddAxis == e.ClickedItem)
            {
                if (dgv_AxisPara.SelectedRows.Count > 0)
                {
                    //得到界面选中的点位
                    string axisId = dgv_AxisPara.SelectedRows[0].Cells["cAxisID"].Value.ToString();
                    string axisName = dgv_AxisPara.SelectedRows[0].Cells["cAxisName"].Value.ToString();
                    //查询到要复制的点位对象，然后复制并添加到点位资源列表中
                    Axis axis = MachineDataManager.Instance.AxisList.SingleOrDefault(p => p.Name == axisName && p.AxisID.ToString() == axisId);
                    if (axis == null) return;

                    Axis copyAxis = axis.DeepCopy();
                    string tempName = string.Empty;

                    for (int i = 0; i < MachineDataManager.Instance.AxisList.Count; i++)
                    {
                        tempName = (copyAxis.Name + $"-{i}");
                        if (MachineDataManager.Instance.AxisList.FindAll(a => a.Name == tempName).Count == 0)
                        {
                            break;
                        }
                    }
                    copyAxis.Name = tempName;
                    MachineDataManager.Instance.AxisList.Add(copyAxis);

                    dgv_AxisPara.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList);

                }
            }
            if (tsmi_DeleteAxis == e.ClickedItem)
            {
                List<string> names = new List<string>();
                var rows = dgv_AxisPara.SelectedRows;
                if (rows.Count > 0)
                {
                    foreach (DataGridViewRow row in rows)
                    {
                        string name = row.Cells["cAxisName"].Value.ToString();
                        names.Add(name);
                    }
                    Dlg_Confirm dlg_Confirm = new Dlg_Confirm("提示", $"确定删除{string.Join(",", names)}?");
                    DialogResult dialogResult = dlg_Confirm.ShowDialog(this);
                    if (dialogResult == DialogResult.OK)
                    {
                        foreach (var name in names)
                        {
                            MachineDataManager.Instance.AxisList.RemoveAll(di => di.Name == name);
                        }
                    }
                    dgv_AxisPara.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList);
                }
                if (tsmi_Refresh == e.ClickedItem)
                {
                    dgv_AxisPara.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList);
                }
            }

        }

        private void dgv_AxisPara_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            dgv_AxisPara.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = e.Exception.Message;
            e.ThrowException = false;
        }

        private void dgv_Home_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }

        private void nud_SpeedPercentage_ValueChanged(object sender, EventArgs e)
        {
            double speedPercentage = (double)nud_SpeedPercentage.Value;
            MachineDataManager.Instance.MotionSpeedPercentage = speedPercentage;
        }

    }
}
